package user

import (
	"go-fiber-demo/models"
	"go-fiber-demo/pkg"
	"go-fiber-demo/pkg/utils/validator"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm/clause"
)

// 注册
func Register(username string, password string) (*models.User, error) {
	user, err := validateUserParams(username, password)
	if err != nil {
		return nil, err
	}

	// 保存到数据库
	gormDb := pkg.GetConfig().GormDb
	cryptPass, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return nil, err
	}
	user.Password = string(cryptPass)
	insertResult := gormDb.Create(user)
	if insertResult.RowsAffected > 0 {
		// 插入成功
		return user, nil
	} else {
		return nil, insertResult.Error
	}
}

// 登录
func Login(username string, password string) (*models.User, error) {
	user, err := validateUserParams(username, password)
	if err != nil {
		return nil, err
	}

	gormDb := pkg.GetConfig().GormDb
	// 根据用户名查找用户
	result := gormDb.Where("username = ?", user.Username).Preload(clause.Associations).Preload("Rules.Permissions").First(user)
	if result.Error != nil {
		return nil, pkg.LoginError{
			Message: "用户不存在",
		}
	}
	// 找到用户后匹配密码
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		return nil, pkg.LoginError{
			Message: "密码不正确",
		}
	}

	return user, nil
}

// -------------- private methods --------------------

// 验证用户输入的数据是否正确
func validateUserParams(username string, password string) (*models.User, error) {
	user := &models.User{
		Username: username,
		Password: password,
	}
	errors := validator.Validate(user)

	if len(errors) > 0 {
		return user, errors[0]
	}

	return user, nil
}
